const { sqlite3 } = require('../../mysql')

// 获取视频列表
const videoList = async (ctx) => {
  try {
    const formData = ctx.query
    const offset = (formData.currentPage - 1) * formData.pageSize
    const limit = Number(formData.pageSize)
    const label = formData.siteClass || ''
    const series = formData.series || ''
    const { id, title, status } = formData
    let keyword = id || title
    const fieldName = id ? 'id' : 'title'

    let query = sqlite3('jav_list')
      .where('label', 'LIKE', `%${label}%`)
      .where('series', 'LIKE', `%${series}%`)

    if (keyword) {
      query = query.where((builder) => {
        builder
          .where(fieldName, 'LIKE', `%${keyword}%`)
          .orWhere('av_id', 'LIKE', `%${keyword}%`)
      })
    }

    if (status) {
      query = query.where('status', 'LIKE', `%${status}%`)
    }

    const [totalData] = await query.clone().count({ total: '*' })
    const data = await query
      .orderBy('id', 'desc')
      .select()
      .limit(limit)
      .offset(offset)
    let total = totalData.total

    if (total === 0 && keyword) {
      const fallbackQuery = sqlite3('jav_list')
        .where('av_id', 'LIKE', `%${keyword}%`)
        .where('label', 'LIKE', `%${label}%`)
        .where('series', 'LIKE', `%${series}%`)

      const [fallbackTotalData] = await fallbackQuery
        .clone()
        .count({ total: '*' })
      const fallbackData = await fallbackQuery
        .orderBy('id', 'desc')
        .select()
        .limit(limit)
        .offset(offset)
      total = fallbackTotalData.total
      data.push(...fallbackData)
    }

    if (keyword) {
      await sqlite3('jav_keyword').insert({ keyword })
    }

    const result = data.map((item) => {
      if (item.label === 'thep') {
        item.bigimage = `https://timg197.top/videos/${item.m3u8}/cover/5_505_259?ih=1`
        item.m3u8 = `https://b2.bttss.cc/videos/${item.m3u8}/g.m3u8?h=3121efe8979c635`
      }
      return item
    })

    ctx.body = {
      success: true,
      data: {
        list: result,
        total,
        pageSize: Number(limit),
        currentPage: Number(formData.currentPage),
      },
    }
  } catch (error) {
    console.error('videoList error:', error)
    ctx.body = { success: false, message: 'Internal Server Error' }
  }
}

// 添加
const videoCreate = async (ctx) => {
  try {
    const formData = ctx.request.body
    const data = await sqlite3('jav_list').insert(formData)
    ctx.body = { success: 200, data: 'success' }
  } catch (error) {
    console.error('videoCreate error:', error)
    ctx.body = { success: false, message: 'Internal Server Error' }
  }
}

// 修改
const videoUpdate = async (ctx) => {
  try {
    const formData = ctx.request.body
    const data = await sqlite3('jav_list')
      .where('id', formData.id)
      .update(formData)
    ctx.body = { success: 200, data: 'success' }
  } catch (error) {
    console.error('videoUpdate error:', error)
    ctx.body = { success: false, message: 'Internal Server Error' }
  }
}

// 删除
const videoDelete = async (ctx) => {
  try {
    const formData = ctx.request.body
    const data = await sqlite3('jav_list').where('id', formData.id).del()
    ctx.body = { success: 200, data: 'success' }
  } catch (error) {
    console.error('videoDelete error:', error)
    ctx.body = { success: false, message: 'Internal Server Error' }
  }
}

// 获取标签
const getLabel = async (ctx) => {
  try {
    const label = ctx.query.label
    const data = await sqlite3('jav_list')
      .where('label', label)
      .distinct()
      .select('series')
    const result = data.map((item, index) => ({
      value: index + 1,
      series: item.series,
    }))

    ctx.body = { success: 200, result }
  } catch (error) {
    console.error('getLabel error:', error)
    ctx.body = { success: false, message: 'Internal Server Error' }
  }
}

module.exports = { videoList, videoCreate, videoUpdate, videoDelete, getLabel }
